import {BASE_URLS} from '@/api/apiConfig/config'

const BaseUrl = BASE_URLS.DEFAULT_BASE_URL;


var Fly = require("flyio/dist/npm/wx");
var fly = new Fly;

fly.config.timeout = 5000;

fly.config.baseURL = BaseUrl;


//添加请求拦截器
fly.interceptors.request.use((request) => {

  // 自定义 headers
  const token = uni.getStorageSync('token');
  // 判断 token 有效性
  const isToken = (request.header || {}).isToken === false;
  console.log('token', token);
  if (token && !isToken) {
    if (!request.header) {
      request.header = {}
    }
    // 自定义token
    request.headers['token'] = token
  }

  // 防止缓存
  if (request.method === 'POST' && request.headers['Content-Type'] !== 'multipart/form-data') {
    request.body = {
      ...request.body
    }
  } else if (request.method === 'GET') {
    request.params = {
      ...request.params
    }
  }
  return request;
});

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    //只将请求结果的data字段返回
    return response.data
  },
  (err) => {
    //发生网络错误后会走到这里
    const code = err.code;
    switch (code) {
      case 401:
        store.isLogin = false;
        uni.showModal({
          title: "尚未登录",
          content: "您尚未登录，是否去登录？",
          showCancel: true,
          success: res => {
            if (res.confirm) {
              uni.redirectTo({
                url: '/pages/login/login'
              })
            } else if (res.cancel) {
              console.log('用户点击取消');
              store.isLogin = false;
              uni.removeStorageSync('token')
            }
          }
        });
        break;
      case 404:
        uni.navigateTo({
          url: "/pages/exception/exception?action=404"
        });
        break;
      case 500:
        uni.navigateTo({
          url: "/pages/exception/exception?action=500"
        });
        break;
      default:
        break;
    }
    return err.data;
  }
);

export default fly
